/**
 * 
 */
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import entity.*;
import utils.DBHelper;
/**
 * @author luoxue
 *
 */
public class SensitiveWordDAO {

	public SensitiveWordDAO()
	{
		super();
	}
	public static SensitiveWordDAO getInstance()
	{
		return new SensitiveWordDAO();
	}
	public String Sensitive(String s)
	{
		ArrayList<String> SensitiveWordList = getArrayList();
		for(String one:SensitiveWordList)
		{
			System.out.println(one);
			s=s.replaceAll(one, "**");
			System.out.println(s);
		}
		return s;
	}
	Connection c;
	PreparedStatement ps;
	ResultSet rs;
	public ArrayList<String> getArrayList()
	{
		ArrayList<String> s=new ArrayList<String>();
		try
		{
	            c = DBHelper.getInstance().getConnection();
	           String sql = "select * from SensitiveList";
	           ps = c.prepareStatement(sql);
	           rs = ps.executeQuery();
	           while(rs.next())
	           {
	        	   String ms = rs.getString("SensitiveWord"); 
	        	   s.add(ms);
	           }
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBHelper.closeConnection(c, ps, rs);
		}
		return s;
	}
	public void add(SensitiveWord sw) {

		try {

			Connection c = DBHelper.getInstance().getConnection();

			String sql = "insert into sensitivelist values(null,?)";
			PreparedStatement ps = c.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
		
			ps.setString(1, sw.getSensitiveWord());
			
			ps.execute();
			
			ResultSet rs = ps.getGeneratedKeys();
			if (rs.next()) {
				int ID =  rs.getInt(1);
				sw.setID(ID);
			}

			DBHelper.closeConnection(c, ps, rs);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void delete(int ID) {
		try {

			Connection c = DBHelper.getInstance().getConnection();

			Statement s = c.createStatement();

			String sql = "delete from sensitivelist where ID = " + ID;

			s.execute(sql);

			DBHelper.closeConnection(c, s, null);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static List<SensitiveWord> getAll(){
		List<SensitiveWord> swlist = new ArrayList<SensitiveWord>();
		try {
			SensitiveWord sw = null;
			Connection c = DBHelper.getInstance().getConnection();

			Statement s = c.createStatement();

			String sql = "select * from sensitivelist";

			ResultSet rs = s.executeQuery(sql);

			while (rs.next()) {

				sw = new SensitiveWord();
				int ID= rs.getInt("ID");
				String sensitiveWord = rs.getString("SensitiveWord");				
				sw.setID(ID);
				sw.setSensitiveWord(sensitiveWord);
				swlist.add(sw);
			}

			DBHelper.closeConnection(c, s, rs);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return swlist;
		
	}
}
